package app.itgungnir.compose.wan.business.login

import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Modifier
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import app.itgungnir.compose.wan.widgets.WanScaffold
import com.google.accompanist.insets.navigationBarsPadding

@Composable
fun LoginScreen(navController: NavController = rememberNavController()) {
    val viewModel = viewModel<LoginViewModel>()
    // UI
    WanScaffold(
        modifier = Modifier.navigationBarsPadding(),
        title = "用户登录",
        navController = navController,
        loadingState = viewModel.loadingState.collectAsState(),
        loadingJob = viewModel.loadingJob,
        errorState = viewModel.errorState.collectAsState(initial = null)
    ) {
        LoginUI(navController = navController) { userName, password ->
            viewModel.login(userName = userName, password = password)
        }
    }
    // State observation
    LoginSuccessObservation(viewModel = viewModel, navController = navController)
}

@Composable
private fun LoginSuccessObservation(
    viewModel: LoginViewModel = viewModel(),
    navController: NavController = rememberNavController()
) {
    val userLoginSuccess = navController.currentBackStackEntry?.savedStateHandle
        ?.getLiveData<Boolean>("user_has_login")?.observeAsState()
    val loginSuccessState by viewModel.loginSuccessState.collectAsState(initial = false)
    LaunchedEffect(key1 = loginSuccessState || (userLoginSuccess?.value == true)) {
        if (loginSuccessState || (userLoginSuccess?.value == true)) {
            navController.previousBackStackEntry?.savedStateHandle?.set("user_has_login", true)
            navController.popBackStack()
        }
    }
}
